<template>
  <el-dialog
    title="权限管理"
    :visible.sync="dialogVisible"
    width="1000px"
    :before-close="handleClose"
  >
    <el-container style="height: 70vh;">
      <!-- 角色区域 -->
      <el-main style="padding: 20px; overflow: hidden;">
        <el-row :gutter="20" style="height: 90%;">
          <!-- 人员角色选择框 -->
          <el-col :span="12" style="height: 100%;">
            <el-card style="height: 100%;">
              <div slot="header">人员角色</div>
              <el-input
                v-model="roleFilterText"
                placeholder="输入关键字过滤"
                style="margin-bottom: 10px;"
              ></el-input>
              <el-scrollbar style="height: calc(100% - 60px);">
                <div
                  v-for="role in filteredRoles"
                  :key="role.id"
                  class="role-item"
                  :style="{
                    backgroundColor: role.id == selectedRole ? '#f0f7ff' : 'transparent',
                  }"
                  @click="handleRoleClick(role)"
                >
                  {{ role.name }}
                </div>
              </el-scrollbar>
            </el-card>
          </el-col>

          <!-- 权限选择框 -->
          <el-col :span="12" style="height: 100%;">
            <el-card style="height: 100%;">
              <div slot="header">权限</div>
              <el-input
                v-model="permissionFilterText"
                placeholder="输入关键字过滤"
                style="margin-bottom: 10px;"
              ></el-input>
              <el-scrollbar style="height: calc(100% - 60px);">
                <div
                  v-for="permission in filteredPermissions"
                  :key="permission.id"
                  class="permission-item"
                  :style="{
                    backgroundColor: permission.isHighlighted === 1 ? '#f0f7ff' : 'transparent',
                  }"
                  @click="handlePermissionClick(permission)"
                >
                  {{ permission.name }}
                </div>
              </el-scrollbar>
            </el-card>
          </el-col>
        </el-row>

        <!-- 操作按钮 -->
        <div style="margin-top: 20px; text-align: right;">
          <el-button type="primary" @click="save">保存</el-button>
          <el-button @click="cancel">取消</el-button>
        </div>
      </el-main>
    </el-container>
  </el-dialog>
</template>

<script>
import { selectUserAndRoleList, selectAuthList, getPermissionList,updateAuth} from "@/api/zhishiku/permission";
export default {
  props: {
    visible: {
      type: Boolean,
      default: false,
    },
    fileId:0
  },
  data() {
    return {

      // 人员角色数据
      roles: [], // 从后端获取
      selectedRole: null, // 选中的人员角色id
      selectedRoleBody: null,//选中当前人员角色对象
      roleFilterText: "", // 人员角色过滤关键字

      // 权限数据
      permissions: [], // 从后端获取
      selectedPermissions: [], // 选中的权限
      permissionFilterText: "", // 权限过滤关键字

      // 左侧面板宽度
      leftWidth: 300, // 默认宽度
      isResizing: false, // 是否正在调整宽度
      
    };
  },
  computed: {
    // 通过计算属性控制弹框显示
    dialogVisible: {
      get() {
        return this.visible;
      },
      set(value) {
        this.$emit("update:visible", value);
      },
    },
    // 过滤后的人员角色
    filteredRoles() {
      return this.roles.filter((role) =>
        role.name.toLowerCase().includes(this.roleFilterText.toLowerCase())
      );
    },
    // 过滤后的权限
    filteredPermissions() {
      return this.permissions.filter((permission) =>
        permission.name.toLowerCase().includes(this.permissionFilterText.toLowerCase())
      );
    },
  },
  watch: {
    //监听人员选中列表变化
    selectedRole(val) {
      console.log(this.fileId)
      this.fetchPermissions(this.selectedRoleBody.type,this.selectedRoleBody.id,this.fileId);
    },

  },
  async created() {
    // 从后端获取数据
    await this.fetchRoles();
    await this.fetchPermissions();
  },
  methods: {
  
    //设置高亮属性
    addHighlightProperty(data) {
      return data.map((item) => {
        // 如果有子节点，递归处理
        if (item.children && item.children.length > 0) {
          item.children = this.addHighlightProperty(item.children);

          // 检查子节点是否有被选中的
          const hasHighlightedChild = item.children.some(
            (child) => child.isHighlighted
          );

          // 设置当前节点的 isHighlighted 状态
          item.isHighlighted = item.isSelected || hasHighlightedChild;
        } else {
          // 如果没有子节点，直接根据 isSelected 设置 isHighlighted
          item.isHighlighted = item.isSelected || false;
        }

        return item;
      });
    },

    // 从后端获取人员角色数据
    async fetchRoles() {
      // 模拟后端数据
      selectUserAndRoleList().then(response => {
        console.log(response)
        this.roles = response;
      })
    },

    // 从后端获取权限数据
    async fetchPermissions(type,refId,fileId) {
      console.log(this.fileId)
      //构建查询条件
      if(refId === undefined || fileId === undefined){
        this.permissions = [];
        return ;
      }
      let formData = new FormData();
      formData.append("type",type);
      formData.append("refId",refId);
      formData.append("fileId",fileId);
      getPermissionList(formData).then(response => {
        console.log(response)
        this.permissions = response;
      })
    },

    // 处理人员角色点击
    handleRoleClick(role) {
      this.roles.forEach((r) => {
        r.isHighlighted = r.id === role.id; // 单选高亮
      });
      this.selectedRole = role.id; // 更新选中角色
      this.selectedRoleBody = role//更新选中角色对象
    },

    // 处理权限点击
    handlePermissionClick(permission) {
      // 使用 Vue.set 确保响应式更新
      if(permission.isHighlighted=== 0){
        permission.isHighlighted = 1;
      }else{
        permission.isHighlighted = 0;
      }

      //控制选中权限列表
      this.selectedPermissions = this.permissions
      .filter(item => item.isHighlighted === 1) // 筛选出 isHighlighted === 1 的项
      .map(item => item.id); // 提取 id 属性值
  
    },

    // 保存操作
    save() {
      console.log("保存操作");
      console.log(this.currentNodeId)
      console.log("选中的角色:", this.selectedRole);
      console.log("选中的权限:", this.selectedPermissions);
      let formData = new FormData();
      formData.append("assignedList",this.selectedPermissions);
      formData.append("refId",this.selectedRole);
      formData.append("fileId",this.fileId);
      formData.append("type",this.selectedRoleBody.type);
      //保存角色
      updateAuth(formData).then(response => {
        console.log(response);
        if(response){
          this.$message({ message: '授权成功', type: 'success' })
        }else{
          this.$message({ message: '授权失败', type: 'warning' })
        }
      })
    },

    // 取消操作
    cancel() {
      console.log("取消操作");
      //刷新授权列表
      if(this.selectedRoleBody != null && this.currentNodeId != 0){
        this.fetchPermissions(this.selectedRoleBody.type,this.selectedRoleBody.id,this.currentNodeId);
      }      
    },

    // 开始调整宽度
    startResize(event) {
      this.isResizing = true;
      document.addEventListener("mousemove", this.resize);
      document.addEventListener("mouseup", this.stopResize);
    },

    // 调整宽度
    resize(event) {
      if (this.isResizing) {
        const newWidth = event.clientX;
        if (newWidth > 200 && newWidth < 600) {
          this.leftWidth = newWidth;
        }
      }
    },

    // 停止调整宽度
    stopResize() {
      this.isResizing = false;
      document.removeEventListener("mousemove", this.resize);
      document.removeEventListener("mouseup", this.stopResize);
    },

    // 关闭弹框
    handleClose(done) {
      //重置
      this.selectedRole= null; // 选中的人员角色id
      this.selectedRoleBody= null;//选中当前人员角色对象
      this.permissions= []; // 从后端获取
      this.selectedPermissions= []; // 选中的权限
      //关闭
      this.$emit("close"); // 通知父组件关闭弹框
    },
  },
};
</script>

<style>
.el-container {
  height: 100vh;
}
.resize-handle {
  position: absolute;
  right: 0;
  top: 0;
  bottom: 0;
  width: 5px;
  background-color: #ddd;
  cursor: col-resize;
  z-index: 1000;
}
.role-item,
.permission-item {
  padding: 10px;
  cursor: pointer;
  border-radius: 4px;
  margin-bottom: 5px;
}
.role-item:hover,
.permission-item:hover {
  background-color: #f5f7fa;
}
</style>